package com.zg.scf.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zg.common.core.dao.scf.CreditDao;
import com.zg.common.core.dao.scf.entity.AccAccount;
import com.zg.common.core.dao.scf.entity.Company;
import com.zg.common.core.dao.scf.entity.Credit;
import com.zg.common.core.dao.scf.entity.Product;
import com.zg.common.core.req.PageReq;
import com.zg.common.core.service.PageBaseService;
import com.zg.common.core.util.DateUtil;
import com.zg.scf.domain.req.StateReq;
import com.zg.scf.domain.req.account.AccAccountPageReq;
import com.zg.scf.domain.req.product.CreditPageReq;
import com.zg.scf.service.CompanyService;
import com.zg.scf.service.CreditService;
import com.zg.scf.enm.StateEnum;
import com.zg.scf.service.ProductService;
import com.zg.scf.util.ScfUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.zg.scf.constant.ScfE.*;


/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/5/22 10:47
 */



@Service
@Slf4j
public class CreditServiceImpl extends PageBaseService<Credit, CreditDao> implements CreditService {

    @Resource
    private ProductService productService;

    @Resource
    private CompanyService companyService;


    protected Page<Credit> pageInfo(Page<Credit> page, PageReq req) {
        CreditPageReq accountPageReq = (CreditPageReq) req; // 需要显式转换
        Page<Credit> pageInfo = baseDao.pageInfo(page, accountPageReq);
        return pageInfo;

    }

    protected  void preRemove(List<Long> ids) {
        for(int i=0;i<ids.size();i++){
            Credit credit = baseDao.getById(ids.get(i));
            if(credit.getState().equals(StateEnum.Y.getValue())){
                CREDIT_IS_NORMAL.happen();
            }
            List<Product> products =productService.listByCredit(credit.getId());
            if(!products.isEmpty()){
                CREDIT_IS_USED.happen();
            }
        }
    }


    protected void preSource(Credit source) {
        Credit Product = baseDao.getById(source.getId());
        if(Product.getState().equals(StateEnum.Y.getValue())){
            CREDIT_IS_NORMAL.happen();
        }
    }

    protected void preAdd(Credit add) {
    }

    public void editState(StateReq req) {
        Credit Product = baseDao.getById(req.getId());
        Product.setState(req.getState());
        baseDao.updateById(Product);
    }

    public List<Credit> listByProductType(Long productTypeId){
        Credit credit = new Credit();
        credit.setProductTypeId(productTypeId);
        return  list(credit);
    }

    /**
     * 授信编号：企业信用代码后四位＋授信申请日＋序列号
     *  例：AM7U  250716 001
     * @return
     */
    public String generateCode(Long bankId){
        Company company = companyService.getById(bankId);
        String creditCode=company.getCreditCode();
        String prefix = creditCode.substring(creditCode.length() - 4);


        // 1. 计算当天起始时间（00:00:00）
        Date beginTime = DateUtil.getBeginOfDay(new Date());
        // 2. 计算当天结束时间（次日00:00:00，左闭右开）
        Date endTime = DateUtil.getToEndOfDay(new Date());

        LambdaQueryWrapper<Credit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Credit::getBankId, bankId)
                .ge(Credit::getCreateTime, beginTime)  // 时间范围起始
                .lt(Credit::getCreateTime, endTime);   // 时间范围结束
        queryWrapper.orderByDesc(Credit::getCreateTime);

        List<Credit> latestCredit = baseDao.list(queryWrapper);
        Integer sequence =1;
        if(!latestCredit.isEmpty()){
            Credit credit = latestCredit.get(0);
            String endfix = credit.getCreditCode().substring(credit.getCreditCode().length() -3);
            sequence =Integer.parseInt(endfix) + 1;
        }
        return ScfUtil.generateCode(prefix, sequence);
    }
}
